package com.food.restaurantpro.observers;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import com.food.restaurantpro.connection.DataHelper;
import com.food.restaurantpro.connection.DataResult;
import com.food.restaurantpro.database.tables.PlaceTable;
import com.food.restaurantpro.managingnetwork.ManagingNetwork;
import com.food.restaurantpro.objects.Place;

public class PlaceObserver implements Observer {

	private PlaceObserver _me = this;
	private boolean hadRegisterObserver = false;
	private ArrayList<Place> mPlaceList;

	public PlaceObserver() {
		registerObserver();
	}

	/**
	 * register observer and get all place. Place khong co api update nen moi
	 * lan vao app la get lai toan bo place
	 */
	public void registerObserver() {
		// call api get all place
		if (ManagingNetwork.isNetworkAvailable()) {
			// show progress
			hadRegisterObserver = true;
			DataHelper.getInstance().addObserver(_me);
			DataHelper.getInstance().getPlaces();
		}
	}

	/**
	 * must call this method in onDestroy of Activity which called
	 * registerObserver
	 */
	public void unRegisterObserver() {
		if (hadRegisterObserver) {
			DataHelper.getInstance().deleteObserver(_me);
			hadRegisterObserver = false;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// close progress
		if (data == null)
			return;
		DataResult result = (DataResult) data;
		switch (result.getMethodName()) {
		case getPlaces:
			if (result.getErrorCode() == null) {
				mPlaceList = (ArrayList<Place>) result.getData();
				if (mPlaceList != null && mPlaceList.size() > 0) {
					PlaceTable.deleteAll();
					PlaceTable.insertPlaceList(mPlaceList);
				}
			}
			unRegisterObserver();
			break;
		default:
			break;
		}
		// Chu y: Observer se post notification den tat ca cac lop da register
		// observer. Va cho nao co phuong thuc trung voi phuong thuc no tra ve
		// thi xu ly
		// cho do, nhung cho khac ko xu ly, vi vay PHAI dat code o trong
		// "case method:"
		// khong dat code o ngoai nay
	}

}
